package com.douxg.learning.java.thread.pool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @ClassName ThreadPoolExecutorL
 * @Description TODO
 * @Author douxg
 * @Date 2020/2/3 17:15
 * @Version 1.0
 */
public class ThreadPoolExecutorL {
    private static final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 3, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(100), new ThreadFactory() {
        private int i = 0;

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r, "pool_StatisActionJob_" + (++i));
            return thread;
        }
    }, new ThreadPoolExecutor.CallerRunsPolicy());
    //    private static final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(10), new ThreadPoolExecutor.CallerRunsPolicy());
    private static final CompletionService<Integer> completionService = new ExecutorCompletionService<>(threadPoolExecutor);

    public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
        List<Future<Integer>> list = new ArrayList<>();
        for (int i = 0; i < 103; i++) {
            final int j = i;
            Future<Integer> submit = completionService.submit(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    TimeUnit.SECONDS.sleep(3);
                    System.out.println(Thread.currentThread().getName() + "*******" + j);
                    return j;
                }
            });
            list.add(submit);
        }
        System.out.println("任务发放完毕");
//        for (Future<Integer> integerFuture : list) {
//            integerFuture.get();
//        }
//        for (int i = 0; i < list.size(); i++) {
//            Future<Integer> take = completionService.take();
//            Integer integer = take.get(1, TimeUnit.HOURS);
//            System.out.println("完成: " + integer);
//        }
        System.out.println("结束");
    }
}
